package cn.com.yusys.yusp.message.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.transaction.Transactional;

import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;

import cn.com.yusys.yusp.admin.service.UserProviderService;
import cn.com.yusys.yusp.commons.mapper.CommonMapper;
import cn.com.yusys.yusp.commons.mapper.QueryModel;
import cn.com.yusys.yusp.commons.util.DateUtil;
import cn.com.yusys.yusp.commons.util.StringUtil;
import cn.com.yusys.yusp.message.domain.MessageContent;
import cn.com.yusys.yusp.message.domain.MessageEvent;
import cn.com.yusys.yusp.message.domain.MessagePool;
import cn.com.yusys.yusp.message.domain.MessagePoolHis;
import cn.com.yusys.yusp.message.domain.MessageSubscribe;
import cn.com.yusys.yusp.message.domain.MessageTemp;
import cn.com.yusys.yusp.message.domain.MessageType;
import cn.com.yusys.yusp.message.repository.mapper.MessageContentMapper;
import cn.com.yusys.yusp.message.repository.mapper.MessageEventMapper;
import cn.com.yusys.yusp.message.repository.mapper.MessagePoolHisMapper;
import cn.com.yusys.yusp.message.repository.mapper.MessagePoolMapper;
import cn.com.yusys.yusp.message.repository.mapper.MessageSubscribeMapper;
import cn.com.yusys.yusp.message.repository.mapper.MessageTempMapper;
import cn.com.yusys.yusp.message.repository.mapper.MessageTypeMapper;
import cn.com.yusys.yusp.message.service.MessageTypeService;
import cn.com.yusys.yusp.message.service.message.MessageConst;
import cn.com.yusys.yusp.message.service.message.filter.UserCustomSelectInterface;
import cn.com.yusys.yusp.message.service.message.filter.UserFilterInterface;
import cn.com.yusys.yusp.message.service.message.mq.MessageSender;
import cn.com.yusys.yusp.message.service.message.util.ParamUtil;
@Service
public class MessageTypeServiceImpl extends MessageTypeService {
	private Logger logger = LoggerFactory.getLogger(MessageTypeServiceImpl.class);
	@Autowired
	private MessageTypeMapper messageTypeMapper;
	
	@Autowired
	private MessageTempMapper messageTempMapper;
	 
	@Autowired
	private MessageSubscribeMapper messageSubscribeMapper;
	
	@Autowired(required=false)
	private List<UserCustomSelectInterface> userCustomSelectService;
	
	@Autowired(required=false)
	private List<UserFilterInterface> userFilterService;
	
	@Autowired
	private MessageEventMapper messageEventMapper;
	
	@Autowired
	private MessageContentMapper messageContentMapper;
	
	@Autowired
	private MessagePoolMapper messagePoolMapper;
	
	@Autowired
	private MessagePoolHisMapper messagePoolHisMapper;
	
	@Autowired
	private MessageSender messageSender;
	
	@Autowired
	private UserProviderService userService;
	
	//private ObjectMapper mapper = new ObjectMapper();
	
	//remarks by Cytus_ at 20180904 修改sonar扫描出现的bug, 此处忽略
	@Override
	protected CommonMapper<?> getMapper() {
		return this.messageTypeMapper;
	}

	@Override
	public List<Map<String,Object>> queryMessageType(QueryModel queryModel) {
		PageHelper.startPage(queryModel.getPage(), queryModel.getSize());
		List<Map<String,Object>> list = messageTypeMapper.queryMessageType( queryModel);
		PageHelper.clearPage();
		for(Map<String,Object> object:list){
			MessageTemp record = new MessageTemp();
			record.setMessageType((String)object.get("messageType"));			
			List<MessageTemp> messageTemps = messageTempMapper.select(record);
			String channelType = "";
			for(MessageTemp messageTem:messageTemps){
				channelType = channelType + messageTem.getChannelType() + ",";
			}
			if(channelType.endsWith(",")){
			    //modify by Cytus_ at 20180904 修改sonar扫描出现的bug, 调用String.substring方法时并不能保证返回调用者，故需要左赋值
			    channelType = channelType.substring(0, channelType.length()-1); 
			}
			object.put("channelType", channelType);
		}
		
		return list;
	}

	@Override
	public int addOrUpdateTemplate(MessageTemp messageTemp) {
		MessageTemp param = new MessageTemp();
		param.setChannelType(messageTemp.getChannelType());
		param.setMessageType(messageTemp.getMessageType());
		List<MessageTemp> list = messageTempMapper.select(param);
		if(list.isEmpty()){
			return messageTempMapper.insertSelective(messageTemp);
		}else{
			return messageTempMapper.updateByPrimaryKeySelective(messageTemp);
		}
	}

	@Override
	public int deleteTemplate(MessageTemp messageTemp) {
		return messageTempMapper.delete(messageTemp);
	}

	@Override
	public MessageTemp getTemplateInfo(MessageTemp messageTemp) {
		MessageTemp messageTempT = new MessageTemp();
		List<MessageTemp> list = messageTempMapper.select(messageTemp);
		if(!list.isEmpty()){
			messageTempT = list.get(0);
		}
		return messageTempT;
	}

	@Override
	public List<Map<String, Object>> queryMessageTypeAndChannel(QueryModel queryModel) {
		PageHelper.startPage(queryModel.getPage(), queryModel.getSize());
		List<Map<String,Object>> list = messageTypeMapper.queryMessageType(queryModel);
		
		for(Map<String,Object> type:list){
			String channel = "";
			MessageTemp record = new MessageTemp();
			record.setMessageType((String)type.get("messageType"));
			List<MessageTemp> messageTemps = messageTempMapper.select(record);
			
			for(MessageTemp messageTempT:messageTemps){
				String messageTempTT = messageTempT.getChannelType();
				if(null!=messageTempTT&&!messageTempTT.equals("")){
					channel = channel + messageTempTT +",";
				}				
			}
			if(channel.length()>0){
				channel = channel.substring(0, channel.length()-1);
			}
			type.put("channelType", channel);
		}
		PageHelper.clearPage();
		return list;
	}

	@Override
	public List<MessageSubscribe> getSubscribeInfo(MessageSubscribe messageSubscribe) {
		return messageSubscribeMapper.select(messageSubscribe);
	}

	@Override
	public int deleteAllMessageSubscribe(MessageSubscribe messageSubscribe) {
		return messageSubscribeMapper.delete(messageSubscribe);
	}

	@Override
	@Async("taskExecutor")
	@Transactional
	public void addOrUpdateMessageSubscribe(MessageSubscribe messageSubscribe) {
		// 先删除
		MessageSubscribe record = new MessageSubscribe();
		record.setChannelType(messageSubscribe.getChannelType());
		record.setMessageType(messageSubscribe.getMessageType());
		record.setSubscribeType(messageSubscribe.getSubscribeType());
		messageSubscribeMapper.delete(record);
		
		String [] subscribeValueStrs = messageSubscribe.getSubscribeValue().trim().split(",");		
		// map去重
		Map<String,String> data = new HashMap<String,String>();
		for(String subscribeValueStr:subscribeValueStrs){
			if(!"".equals(subscribeValueStr)){
				data.put(subscribeValueStr, subscribeValueStr);
			}
		}
		
		// 再新增
		String[] valueArray = new String[data.size()];
		String keys[] = data.values().toArray(valueArray);
		for(String key:keys){
			MessageSubscribe messageSubscribeT = new MessageSubscribe();
			messageSubscribeT.setChannelType(messageSubscribe.getChannelType());
			messageSubscribeT.setMessageType(messageSubscribe.getMessageType());
			messageSubscribeT.setSubscribeType(messageSubscribe.getSubscribeType());
			messageSubscribeT.setSubscribeValue(key);
			//messageSubscribeT.setOpUserNo(SecurityUtils.getCurrentUserLogin());
			messageSubscribeMapper.insertSelective(messageSubscribeT);
		}			
	}


	@Override
	@Async("taskExecutor")
	@Transactional
	public void sendRealTimeMessageWithOutTemplate(String channelType, String users, String msg,Map<String,String> otherParam) {
		// 获取实时消息需要发送的人
		Set<String> temp = getRealTimeUsers(users);
		
		if(temp.isEmpty()){
			logger.error("No target sender provided, unable to send message");	
			return;
		}
		if(channelType!=null){
			if(this.isFixedChannel(channelType)){
				// 生成消息事件
				String eventNo = this.generateEvenNo();			
				Map<String,String> param = new HashMap<String,String>();
				param.putAll(otherParam);
				param.put("channelType", channelType);
				param.put("users", users);
				param.put("msg", msg);			
				generateEvent( eventNo,MessageConst.NO_TEMPLATE, param);
				
				// 生成消息内容
				generateContent( eventNo,MessageConst.NO_TEMPLATE, channelType,msg,new Short("0"),otherParam.get("timeStart"),otherParam.get("timeEnd"),otherParam.get("title"));
				
				// 插入消息队列
				for(String userIdTT : temp){
					generateMessage(MessageConst.NO_TEMPLATE, userIdTT, channelType, eventNo,MessageConst.MSSSAGE_LEVEL_H,otherParam.get("timeStart"),otherParam.get("timeEnd"),"0");
				}
				
			}else{
				logger.error("Unsupported channel type, unable to send message"+channelType);
			}		
		}else{
			logger.error("No channel type provided, unable to send message");	
		}			
	}
	
	private String generateEvenNo(){		
		return "E" + DateUtil.formatDate(DateUtil.PATTERN_DATETIME_COMPACT_SSS) + StringUtil.getUUID().substring(0, 7);	 
	}
	
	private String generatePkNo(){		
		return "P" + DateUtil.formatDate(DateUtil.PATTERN_DATETIME_COMPACT_SSS) + StringUtil.getUUID().substring(0, 10);	 
	}
	
	private boolean isFixedChannel(String channelType){
		if(MessageConst.EMAIL.equals(channelType)){
			return true;
		}else if(MessageConst.MOBILE.equals(channelType)){
			return true;
		}else if(MessageConst.SYSTEM.equals(channelType)){
			return true;
		}else{
			return false;
		}
	}
	
	@SuppressWarnings("rawtypes")
    private void generateEvent(String eventNo,String messageType,Map param){
		// 生成消息事件
		MessageEvent messageEvent = new MessageEvent();
		messageEvent.setCreateTime(DateUtil.formatDate(DateUtil.PATTERN_DATETIME_COMPACT_SSS));
		messageEvent.setEventNo(eventNo);
		messageEvent.setMessageType(messageType);		
		messageEvent.setTemplateParam(/*JSON.toJSONString(param)*/JSONObject.toJSONString(param));
		messageEventMapper.insertSelective(messageEvent);
	}
	
	private void generateContent(String eventNo,String messageType,String channelType,String msgContent,Short sendNum,String timeStart,String timeEnd,String emailTitle){
		// 生成消息内容
		MessageContent messageContent = new MessageContent();
		messageContent.setEventNo(eventNo);
		messageContent.setMessageType(messageType);
		messageContent.setChannelType(channelType);
		messageContent.setContent(msgContent);		
		messageContent.setSendNum(sendNum);
		messageContent.setTimeEnd(timeEnd);
		messageContent.setTimeStart(timeStart);
		messageContent.setEmailTitle(emailTitle);
		messageContentMapper.insertSelective(messageContent);
	}
	
	private void generateMessage(String messageType,String userNo,String channelType,String eventNo,String messageLevel,String startTime,String endTime,String isTime){
		
		try {
			MessagePool messagePool = new MessagePool();
			messagePool.setChannelType(channelType);
			messagePool.setPkNo(generatePkNo());
			messagePool.setCreateTime(DateUtil.formatDate(DateUtil.PATTERN_DATETIME_COMPACT_SSS));
			messagePool.setEventNo(eventNo);
			messagePool.setMessageLevel(messageLevel);
			messagePool.setState(MessageConst.SENDING);
			messagePool.setUserNo(userNo);
			messagePool.setTimeStart(startTime);
			messagePool.setTimeEnd(endTime);
			messagePool.setPkHash(RandomUtils.nextInt(0, MessageConst.MAX_NUMBER) + 1);	
			messagePool.setMessageType(messageType);
			messagePoolMapper.insertSelective(messagePool);
			if("1".equals(isTime)){// 定时消息
				messageSender.sendDelayMessage(JSONObject.toJSONString(messagePool)/*mapper.writeValueAsString(messagePool)*/, Integer.parseInt(messageLevel));
			}else{// 非定时消息
				messageSender.sendMessage(JSONObject.toJSONString(messagePool)/*mapper.writeValueAsString(messagePool)*/, Integer.parseInt(messageLevel));
			}
		} catch (Exception e) {
			logger.error("Failed to generate message【Message type ："+messageType+";Channel type："+channelType+";Target user ID:"+userNo+"】\n"+e);
			e.printStackTrace();
		}
	}
		
	private Set<String> getRealTimeUsers(String users){
		Set<String> temp = new HashSet<String>();
		if(users!=null){
			String[] usersT = users.split(",");
			for(String userId:usersT){
				if(null!=userId&&!"".equals(userId.trim())){
					temp.add(userId.trim());
				}						
			}
		}
		return temp;		
	}
	
	@Override
	@Async("taskExecutor")
	public void sendRealTimeMessageWithTemplate(String messageType, String channelType, String users, Map<String,Object> param) {
		
		MessageType  messageTypeT  = messageTypeMapper.selectByPrimaryKey(messageType);
		if(null!=messageTypeT){
			if("S".equals(messageTypeT.getTemplateType())){
				logger.debug("According to the unique identification of the message, it is found that the message to be sent is【real-time message】:"+messageType);	
				String eventNo = this.generateEvenNo();	
				generateEvent( eventNo, messageType, param);
				// 获取实时消息需要发送的人
				Set<String> temp = getRealTimeUsers(users);
				
				// 用户自定义选人
				Set<String> userCustom = userCustomSelect( messageType, param);
				temp.addAll(userCustom);
				
				// 用户自定义过滤
				Set<String> userSet = userFilter( messageType, temp, param);
				
				// 获取实时消息下的模板
				MessageTemp record = new MessageTemp();
				record.setMessageType(messageType);
				if(channelType!=null&&!"".equals(channelType)){
					record.setChannelType(channelType);
				}
				List<MessageTemp> list = messageTempMapper.select(record);
				if(list.isEmpty()){
					logger.error("【Real-time message】:"+messageType+" The orresponding channel is not configured by "+channelType+" template");
					return;
				}
				
				for(MessageTemp messageTemp:list){
					String channelTypeT = messageTemp.getChannelType();
					if(isFixedChannel(channelTypeT)){
						// 替换模板内容
						String messageContent = ParamUtil.replaceParam(messageTemp.getTemplateContent(),param);
						
						// 生成消息内容
						generateContent(eventNo,messageTemp.getMessageType(), channelTypeT,messageContent,messageTemp.getSendNum(),messageTemp.getTimeStart(),messageTemp.getTimeEnd(),messageTemp.getEmailTitle());
						
						for(String userId:userSet){
							// 生成消息队列
							generateMessage(messageType,userId, channelTypeT, eventNo,messageTypeT.getMessageLevel(),messageTemp.getTimeStart(),messageTemp.getTimeEnd(),"0");
						}
					}else{
						logger.error("Unsupported channel type, unable to send message:{}", channelType);
					}				
				}
										
			}else{
				logger.warn("The unique identification of the message is not【Real-time type】:{}", messageType);	
			}
		}else{
			logger.error("The unique identification of the message does not exist:{}", messageType);
		}
	}

	@Override
	@Async("taskExecutor")
	public void sendSubscribeMessage(String messageType,String channelType, Map<String,Object> param) {
		MessageType messageTypeT = messageTypeMapper.selectByPrimaryKey(messageType);
		if (null != messageTypeT) {
			if ("D".equals(messageTypeT.getTemplateType())) {
				logger.debug("According to the unique identification of the message, it is found that the message to be sent is【Subscription message】:" + messageType);
				// 生成消息事件
				String eventNo = this.generateEvenNo();	
				generateEvent( eventNo, messageType, param);
				
				// 获取模板
				MessageTemp record = new MessageTemp();
				record.setMessageType(messageType);
				if(channelType!=null&&!"".equals(channelType)){
					record.setChannelType(channelType);
				}
				List<MessageTemp> list = messageTempMapper.select(record);
				if(list.isEmpty()){
					logger.error("【Subscription message】:"+messageType+" The orresponding channel is not configured by "+channelType+" template");
					return;
				}
				
				for(MessageTemp messageTemp:list){
					String channelTypeT = messageTemp.getChannelType();
					if(isFixedChannel(channelTypeT)){
						// 替换模板内容
						String messageContent = ParamUtil.replaceParam(messageTemp.getTemplateContent(),param);
						
						// 生成消息内容
						generateContent(eventNo,messageTemp.getMessageType(), channelTypeT,messageContent,messageTemp.getSendNum(),messageTemp.getTimeStart(),messageTemp.getTimeEnd(),messageTemp.getEmailTitle());
						
						// 获取模板的订阅用户
						Set<String> userSet = getSubscribeUser( messageType, channelTypeT,param.get("sendUserId")) ;
						// 用户自定义选人
						Set<String> userCustom = userCustomSelect( messageType, param);
						userSet.addAll(userCustom);
						
						// 用户自定义过滤
						Set<String> userSetT = userFilter( messageType, userSet, param);
						for(String userId:userSetT){
							// 生成消息队列
							generateMessage(messageType,userId, channelTypeT, eventNo,messageTypeT.getMessageLevel(),messageTemp.getTimeStart(),messageTemp.getTimeEnd(),messageTemp.getIsTime());
						}
					}else{
						logger.error("Unsupported channel type, unable to send message"+channelType);
					}
				}
			} else {
				logger.error("The unique identification of the message is not【Subscription type】"+messageType);
			}
		} else {
			logger.error("The unique identification of the message does not exist:" + messageType);
		}
	}
	
	private Set<String> getSubscribeUser(String messageType, String channelType,Object sendUserId) {

		// 遍历模板下的订阅人员
		Set<String> userSet = new HashSet<String>();

		MessageSubscribe messageSubscribe = new MessageSubscribe();
		messageSubscribe.setMessageType(messageType);
		messageSubscribe.setChannelType(channelType);
		List<MessageSubscribe> messageSubscribes = messageSubscribeMapper.select(messageSubscribe);
		
		
		Set<String> userSetUser = new HashSet<String>();
		Set<String> orgSetUser = new HashSet<String>();
		Set<String> roleSetUser = new HashSet<String>();
		Set<String> dutySetUser = new HashSet<String>();
		Set<String> relationshipSetUser = new HashSet<String>();
		for (MessageSubscribe subscribe : messageSubscribes) {
			if ("U".equals(subscribe.getSubscribeType())) {// 用户订阅
				if (null != subscribe.getSubscribeValue() && !"".equals(subscribe.getSubscribeValue().trim())) {
					userSet.add(subscribe.getSubscribeValue().trim());
					userSetUser.add(subscribe.getSubscribeValue().trim());
				}
			} else if ("O".equals(subscribe.getSubscribeType())) {
				if (null != subscribe.getSubscribeValue() && !"".equals(subscribe.getSubscribeValue().trim())) {
					List<String> userList = userService.queryUserByOrgId(subscribe.getSubscribeValue());//orgMapper.selectOrgUser(subscribe.getSubscribeValue());
					for(String userNo:userList){
						if(null!=userNo&&!"".equals(userNo)){
							userSet.add(userNo);
							orgSetUser.add(userNo);
						}						
					}
				}
			} else if ("R".equals(subscribe.getSubscribeType())) {
				if (null != subscribe.getSubscribeValue() && !"".equals(subscribe.getSubscribeValue().trim())) {
					List<String> userList = userService.queryUserByRoleId(subscribe.getSubscribeValue());//orgMapper.selectRoleUser(subscribe.getSubscribeValue());
					for(String userNo:userList){
						if(null!=userNo&&!"".equals(userNo)){
							userSet.add(userNo);
							roleSetUser.add(userNo);
						}						
					}
				}
			} else if ("G".equals(subscribe.getSubscribeType())) {
				if (null != subscribe.getSubscribeValue() && !"".equals(subscribe.getSubscribeValue().trim())) {
					List<String> userList = userService.queryUserByDutyId(subscribe.getSubscribeValue());//orgMapper.selectDutyUser(subscribe.getSubscribeValue());
					for(String userNo:userList){
						if(null!=userNo&&!"".equals(userNo)){
							userSet.add(userNo);
							dutySetUser.add(userNo);
						}						
					}
				}
			}else if ("X".equals(subscribe.getSubscribeType())) {
				String subscribeValue = subscribe.getSubscribeValue();
				if (null != subscribeValue && !"".equals(subscribeValue.trim())) {
					subscribeValue = subscribeValue.trim();
					if(null!=sendUserId&&!"".equals(sendUserId)){
						if(subscribeValue.equals(MessageConst.UP_LEVEL)){//上级机构
							List<String> userOrg = userService.queryOrgsByUserId(StringUtil.replaceNullByObj(sendUserId));//orgMapper.selectUserOrg((String)sendUserId);//获取用户机构
							if(userOrg.isEmpty()){
								logger.error("sender ID "+sendUserId+" do not has organization, unable to calculate the relative relationship");
							}else{
								List<String> userOrgT = userService.queryUpOrgByOrgId(userOrg.get(0));//orgMapper.selectUpOrg(userOrg.get(0));
								if(userOrgT.isEmpty()){
									logger.error("sender ID "+sendUserId+" do not has superior organization, unable to calculate the relative relationship");
								}else{
									/*List<String> param = new ArrayList<String>();
									param.addAll(userOrgT);*/
									List<String> userT = userService.queryUserByOrgIds(userOrgT);//orgMapper.selectOrgsUsers(param);
									for(String userNo:userT){
										if(null!=userNo&&!"".equals(userNo)){
											userSet.add(userNo);
											relationshipSetUser.add(userNo);
										}						
									}
								}
							}
						}else if(subscribeValue.equals(MessageConst.SAME_LEVEL)){//同级机构
							List<String> userOrg = userService.queryOrgsByUserId(StringUtil.replaceNullByObj(sendUserId));// orgMapper.selectUserOrg((String)sendUserId);//获取用户机构
							if(userOrg.isEmpty()){
								logger.error("sender ID "+sendUserId+" do not has organization, unable to calculate the relative relationship");
							}else{
								List<String> userOrgT = userService.queryUpOrgByOrgId(userOrg.get(0));//orgMapper.selectUpOrg(userOrg.get(0));
								if(userOrgT.isEmpty()){
									logger.error("sender ID "+sendUserId+" do not has superior organization, unable to calculate the relative relationship");
								}else{									
									List<String> userSamOrg = userService.queryOrgsByUpOrgId(userOrgT.get(0));//orgMapper.selectUpOrgOrgs(userOrgT.get(0));									
									List<String> param = new ArrayList<String>();
									param.addAll(userSamOrg);
									List<String> userT = userService.queryUserByOrgIds(userSamOrg);//orgMapper.selectOrgsUsers(param);
									for(String userNo:userT){
										if(null!=userNo&&!"".equals(userNo)){
											userSet.add(userNo);
											relationshipSetUser.add(userNo);
										}						
									}
								}
							}
						}else{
							logger.error("Non-existing institutional relationship:" + subscribeValue);
						}
						
					}else{
						logger.error("The sender ID [sendUserid] is empty, unable to calculate the relative relationship");
					}
				}
			}else{
				logger.error("Non-existing subscription type:" + subscribe.getSubscribeType());
			}
		}
		
		//求并集
		if(!userSetUser.isEmpty()){
			userSet.retainAll(userSetUser);
		}
		if(!dutySetUser.isEmpty()){
			userSet.retainAll(dutySetUser);
		}
		if(!roleSetUser.isEmpty()){
			userSet.retainAll(roleSetUser);
		}
		if(!orgSetUser.isEmpty()){
			userSet.retainAll(orgSetUser);
		}
		if(!relationshipSetUser.isEmpty()){
			userSet.retainAll(relationshipSetUser);
		}
			
		return userSet;
	}
	
	private Set<String> userCustomSelect(String messageType,Map<String,Object> param) {
		// 自定义人员选择
		Set<String> temp = new HashSet<String>();
		if(null!=userCustomSelectService&&!userCustomSelectService.isEmpty()){
			for(UserCustomSelectInterface userCustomSelect:userCustomSelectService){
				if(userCustomSelect.isFixed(messageType)){
					temp = userCustomSelect.selectUsers(param);
					break;
				}
			}
		}
		return temp;
	}
	
	private Set<String> userFilter(String messageType, Set<String> userIds,Map<String,Object> param) {
		// 自定义人员过滤
		if (null != userFilterService && !userFilterService.isEmpty()) {
			for (UserFilterInterface userFilter : userFilterService) {
				if (userFilter.isFixed(messageType)) {
					return userFilter.afterFilterUser(userIds, param);
				}
			}
		}
		return userIds;
	}

	@Override
	public List<Map<String, Object>> queryMessageResult(QueryModel queryModel) {
		PageHelper.startPage(queryModel.getPage(), queryModel.getSize());
		List<Map<String,Object>> list = messagePoolHisMapper.queryMessageResult(queryModel);
		PageHelper.clearPage();
		return list;
	}
	
	@Override
	public List<Map<String, Object>> queryMessagePool(QueryModel queryModel) {
		PageHelper.startPage(queryModel.getPage(), queryModel.getSize());
		List<Map<String,Object>> list = messagePoolMapper.queryMessagePool(queryModel);
		PageHelper.clearPage();
		return list;
	}

	@Override
	public int sendAgain(String[] pkNoArray) {
		if(null!=pkNoArray){			
			for(String pkNo:pkNoArray){
				if(!"".equals(pkNo)){
					sendAgain( pkNo);
				}
			}
			return 0;
		}else{
			return 1;
		}	
	}
	
	@Transactional
	public void sendAgain(String pkNo){
		try {
			MessagePoolHis messagePoolHis  = messagePoolHisMapper.selectByPrimaryKey(pkNo);
			messagePoolHisMapper.deleteByPrimaryKey(pkNo);

			MessagePool messagePool = new MessagePool();
			messagePool.setChannelType(messagePoolHis.getChannelType());
			messagePool.setCreateTime(messagePoolHis.getCreateTime());
			messagePool.setEventNo(messagePoolHis.getEventNo());
			messagePool.setMessageLevel(messagePoolHis.getMessageLevel());
			messagePool.setPkHash(messagePoolHis.getPkHash());
			messagePool.setPkNo(messagePoolHis.getPkNo());
			messagePool.setState(MessageConst.SENDING);
			messagePool.setUserNo(messagePoolHis.getUserNo());
			messagePool.setTimeStart(messagePoolHis.getTimeStart());
			messagePool.setTimeEnd(messagePoolHis.getTimeEnd());
			messagePool.setMessageType(messagePoolHis.getMessageType());
			messagePoolMapper.insertSelective(messagePool);
			messageSender.sendMessage(JSONObject.toJSONString(messagePool)/*mapper.writeValueAsString(messagePool)*/, 5);
		} catch (Exception e) {
			logger.error("Failed to resend message【primary key: "+pkNo+"】\n"+e);
			e.printStackTrace();
		}
	}

	@Override
	public int top(String[] pkNoArray) {
		if(null!=pkNoArray){			
			for(String pkNo:pkNoArray){
				if(!"".equals(pkNo)){
					top( pkNo);
				}
			}
			return 0;
		}else{
			return 1;
		}	
	}
	
	private void top(String pkNo){
		try {
			
			MessagePool messagePool = new MessagePool();
			messagePool.setPkNo(pkNo);
			messagePool.setMessageLevel(MessageConst.MSSSAGE_LEVEL_H);
			messagePoolMapper.updateByPrimaryKeySelective(messagePool);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
